【问题标题】:what are the differences between this['key'] and $data['key'] for v-model?v-model 的 this['key'] 和 $data['key'] 有什么区别?
【发布时间】:2023-03-09 02:22:01
【问题描述】:

请看下面的sn-p,有3个demo,前2个demo工作正常(v-model工作正常)。

但是对于最后一个,当您在<input> 中输入内容时,您会看到this['test 1'] 不会更新。 <h2>Name:<span>{{this['test 1']}}</span></h2> 始终是初始值。

似乎v-modelthis['test 1'] 绑定了一个克隆。对于这种情况,我们必须使用$data['test 1']

有谁知道造成这些差异的原因是什么?

app = new Vue({
  el: "#app",
  data () {
    return {
    'test': "Cat in Boots",
    'test 1': 'Snow White'
    }
  },
  methods: {
    testCase1: function(){
      this['test'] = 'I am Cat in Boots' //works
      this['test 1'] = 'I am Cat in Boots' //works
    }
  }
})
span {
  background-color:green
}

a {
  color:red
}
<script src="https://unpkg.com/vue@2.5.16/dist/vue.js"></script>
<div id="app">
    <button @click="testCase1()">Test Case 1</button>It will change the data successfully.
    <h2>Name:<span>{{test}}</span></h2>
    <input v-model="test">
    <h2>Name:<span>{{$data['test 1']}}</span></h2>
    <input v-model="$data['test 1']">
    <h2>Name:<span>{{this['test 1']}}</span></h2>
    <input v-model="this['test 1']"><a>Type something in this input, the name will not be changed.</a>
</div>

【问题讨论】:

  • 确实是非常奇怪的行为。这就是为什么你不应该像访问数组那样访问组件的数据
  • @Phiter 通常我们不会使用一个带空格的字符串作为一个组件数据的一个键。所以我们不会遇到上述情况。我只是好奇是什么原因造成的。
  • 看起来您最终使用this 引用了另一个对象。检查以确保您实际上没有在编辑某些全局变量。

标签: javascript vue.js


【解决方案1】:

你不能在模板中使用this,因为它不引用模板中的组件,所以在这种情况下使用$data是必要的

【讨论】:

    【解决方案2】:

    根本原因是

    正如Vue的作者所说:this会根据你所在的函数作用域在编译的模板中发生变化。

    所以不要在模板中使用this

    查看来自 Vue 作者的反馈https://github.com/vuejs/vue/issues/8080

    你也可以在github查看directive->model.js的源代码。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-11-20
      • 2012-04-18
      • 2019-08-01
      • 2021-09-06
      • 1970-01-01
      • 2013-09-22
      • 1970-01-01
      • 2013-06-24
      相关资源
      最近更新 更多