vue.js - VueJS 和动态标题

标签 vue.js vuejs2 vue-component vue-router

尝试使用 vue-meta

我不明白如何根据 XHR 响应设置标题。到目前为止,我有:

<script>
    export default {
        name: 'Model',
        data() {
            return {
                model: [],
            }
        },
        metaInfo: {
            title: 'Default Title',
            titleTemplate: '%s - site slogan'
        },
        methods: {
            getModels() {
                window.axios.get(`/api/${this.$route.params.manufacturer}/${this.$route.params.model}`).then((response) => {
                    this.model = response.data;
                    this.metaInfo.title = response.data.model_name; // THIS NOT WORKING
                });
            }
        },
        watch: {
            $route(to, from) {
                if ( to.name === 'model' ) {
                    this.getModels();
                }
            },
        },
        created() {
            this.getModels();
        }
    }
</script>

当我尝试设置
this.metaInfo.title = response.data.model_name;

出现错误:未捕获( promise 中)TypeError:无法设置未定义的属性“标题”

所以 this.metaInfo 是未定义的......

我需要我的头衔基于 XHR 请求的响应。

最佳答案

需要使用metaInfo的函数形式并让它从 react 数据中获取更新

<script>
export default {
    data() {
        return {
            title: "Default Title",
            // ...
        };
    },
    metaInfo() {
        return {
            title: this.title,
            // ...
        };
    },
    methods: {
        getModels() {
            window.axios.get("url...").then((response) => {
                this.title = response.data.model_name;
            });
        }
    },
    //  ...

关于vue.js - VueJS 和动态标题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51921546/

相关文章:

javascript - 如何告诉vuefire的firestore在 "created"钩子(Hook)之后执行?

javascript - iframe 收到 postMessage 内容后加载所有内容

javascript - 为什么这个去抖函数会破坏 "this"?

javascript - VueJs 引用选中的对象

javascript - 使用 VueJS 进行 location.reload

javascript - Vue JS - 如何使用基于可变数据的模型创建动态输入字段

vue.js - 如何扩展从 npm 包导入的 vue 组件?

javascript - 如何在非 vue 网络应用程序中使用 Vuejs 网络组件作为输入元素?

javascript - Vue : how to update cart total price when user increment item in child component

javascript - 将焦点设置在第二级引导模式中包含的输入控件上