【问题标题】:update data in component from Vue.directive从 Vue.directive 更新组件中的数据
【发布时间】:2016-03-03 18:16:27
【问题描述】:

我有一个指令需要更新 Vue.component 中的数据。如何设置值?这是我的代码:

Vue.directive('loggedin', function(value) {
    console.log('loggedin = ' + value);
    vm.$set('loggedIn', value);
});

vm.$set('loggedIn', value) 不起作用。我收到以下错误: 未捕获的类型错误:无法读取未定义的属性“$set”

var ck = Vue.component('checkout', {
    template: '#checkout-template',

    props: ['list'],

    data: function() {
        return {
            loggedIn: '',
            billingAddr: [],
            shippingAddr: [],

        }
    },
});

传递的值是“真”或“假”。

编辑

我需要将<div v-loggedin="true"></div> 绑定到组件中的数据值并将其设置为“true”。我不需要双向绑定。

也许我用错了方法。基本上,我从服务器获取 login 的值,并且需要在组件的数据中将我的 loggedIn 值设置为 true 或 false。

【问题讨论】:

标签: vue.js


【解决方案1】:

我不确定你是如何使用你的指令的,所以我只是做一个假设。如果我错了,请纠正我。

看看twoWay property(不过你可能需要使用对象语法):

Vue.directive('loggedin', {
  twoWay: true, // Setup the two way binding
  bind: function () {
  },
  update: function (newValue) {
    console.log('loggedin = ' + value);
    this.set(newValue); // Set the new value for the instance here
  },
  unbind: function () {
  }
});

然后你可以像这样使用指令(loggedIn 是你之后要写入的属性,它也可以作为初始值):

<yourelement v-loggedin="loggedIn">...</yourelement>

关于您的修改

由于您只想将数据从服务器传递到组件,因此您最好只使用props

var ck = Vue.component('checkout', {
    template: '#checkout-template',

    props: ['list', 'loggedIn'],

    data: function() {
        return {
            billingAddr: [],
            shippingAddr: [],

        }
    },
});

然后在使用你的组件时,传递它:

<checkout :loggedIn="true">
    ...
</checkout>

【讨论】:

    【解决方案2】:

    我决定走另一条路。必须有一种更简单的方法来做到这一点。所以,这就是我所做的。

    我正在通过 vm 上的“created”函数执行 ajax 请求来检查用户是否已登录。然后我用 true 或 false 更新 vm 中的 auth 变量。

    var vm = new Vue({
        el: 'body',
        data: {
            auth: false,
    
        },
    
        methods: {
            getData: function() {
    
                this.$http.get('{!! url('api/check-for-auth') !!}').then(function(response) { 
                    this.auth = response.data;
                }.bind(this));
            },
        },
    
        created: function() {
            this.getData();
        },
    });
    

    在组件中,我创建了一个名为“auth”的道具,并将其绑定到 vm 上的 auth 数据。

    var ck = Vue.component('checkout', {
        template: '#checkout-template',
        props: ['list', 'auth'],
        data: function() {
            return {
                user: [],
                billingAddr: [],
                shippingAddr: [],
    
            }
        },
    
    });
    

    还有我的组件

    <checkout :list.sync="cartItems" :auth.sync="auth"></checkout>
    

    感谢大家的帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-05-06
      • 2019-02-17
      • 2017-08-15
      • 2017-04-16
      • 1970-01-01
      • 2017-04-28
      相关资源
      最近更新 更多