Vue中的$set方法不能给通过函数放回的data添加属性吗?

图片描述

如上图,我在vue实例根组件下定义了一个app-father组件,并且定义了一个方法 getData,当调用getData方法时,为data添加两个值为参数值的属性,但是,这样并不可行额...

阅读 2.3k
1 个回答

你如果直接如此,会触发Vue警告。

Property or method is not defined on the instance but referenced during render. Make sure to declare reactive data properties in the data option.

最好是事先定义好数据结构。

如果你非要这么做,也是可以的,如上,你可以为这2个变量定义个容器,比如

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
</head>
<body>
  <div id="app">
    <app-father />
  </div>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.0.3/vue.js"></script>
  <script>
  
    new Vue({
        el: '#app',
        components: {
          'app-father': {
            methods: {
              getData(sex, height) {
                this.$set(this.container, 'sex', sex);
                this.$set(this.container, 'height', height);
              }
            },
            template: `<div>Sex is {{ container.sex }}, Height is {{ container.height }}</div>`,
            data() {
              return {
                container: {
                  //sex: '',
                  //height: ''
                }
              }
            },
            mounted() {
              this.getData(1, 1);
            }
          }
        }
    
    })
    
  </script>
</body>
</html>

也可以在线查看

https://jsbin.com/fejucihuli/...

推荐问题