【问题标题】:Cannot access a state property in Template Vue无法访问模板 Vue 中的状态属性
【发布时间】:2018-09-16 10:35:42
【问题描述】:

我是 Vue 的新手。我正在尝试从在线视频中学习 Vue。在下面的 sn-p 中,在 Counter 对象中,如果我将模板更改为渲染函数,代码就会开始工作。

我不明白为什么?

-----HTML----

<div id="app">
  <counter></counter>
  <counter></counter>
  <counter></counter>
  <button @click="inc">increment</button>
</div>

-----脚本标签------

const state = new Vue({
 data: {
    count: 0
 },
  methods: {
    inc() {
        this.count++;
    }
  }
});

const Counter = {
    template: `<div>{{state.count}}</div>`
}

new Vue({
  el: '#app',
  components: {
    Counter
  },
  methods: {
    inc() {
        state.inc();
    }
  }
})

如果我将 Counter 中的模板更改为此,它正在工作

render: h => h('div', state.count)

【问题讨论】:

  • 这看起来使用 Vuex 比使用多个 Vue 实例效果更好
  • 嗨,Phil,这是一些东西,我只是在尝试。根据我的理解,模板将被转换为渲染函数,所以理想情况下这应该与模板一起使用。

标签: javascript vue.js


【解决方案1】:

state 是一个 Vue 实例,因此data 属性中的变量可以作为state 中的属性访问,即:state.countthis.count 内部在state 实例中。

因为state.count 是有效的,您可以在state 实例下方的任何位置访问它。

然后render: h =&gt; h('div', state.count) 变为有效。

现在,template 中访问的任何属性都必须是 Vue 实例或组件的内部属性,或者是 Countthis 的属性。

因为Counter组件中的模板会被转换成这个对应的渲染函数:

render(h) {
    return h('div', this.state.count)
}

{{state.count}} 不是指state.count 变量,而是Counter 组件this.state.count 的一个属性。

所以为了举例(在实际项目中你不会做任何事情),这里是如何使state.countCounter 模板中有效:

const Counter = {
    template: `<div>{{state.count}}</div>`,
    data: () => ({
        state: {
            count: state.count
        }
    })
}

【讨论】:

  • 模板也将被转换为仅渲染功能 ryt?
  • 是的,他们会的。从该模板,它将被转换为render: h =&gt; h('div', this.state.count)
猜你喜欢
  • 2013-06-18
  • 1970-01-01
  • 2014-07-31
  • 2020-06-14
  • 1970-01-01
  • 2016-04-10
  • 1970-01-01
  • 2021-07-06
  • 2019-07-27
相关资源
最近更新 更多