Vue.js在组件外部设置数据 [英] Vue.js set data outside component

查看:91
本文介绍了Vue.js在组件外部设置数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个组件,我想在组件外设置一个数据项

I've got a component and I would like to set a data item outside the component.

我如何使用指令执行此操作?

How would I do this with a directive?

我在考虑这样的事情:

Vue.directive('init', {
    bind: function(el, binding, vnode) {
        vnode.context[binding.arg] = binding.value;
    }
});

但它不起作用:

Vue.directive('init', {
  bind: function(el, binding, vnode) {
    vnode.context[binding.arg] = binding.value;
  }
});

Vue.component('test', {
	template: '<p>{{date}}</p>',
  data() {
  	return {
    		date: ""
    }
  }
});

new Vue({
  el: '#app'
})

<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.4.1/vue.js"></script>


<div id="app">
  <test v-init:date="'2017-07-20 09:11:42'"></test>
</div>

任何想法如何让这个工作?

Any Idea how I would get this to work?

- 编辑 -

我不想为此使用道具!我有很多很多领域。

I don't want to use props for this! I've lots and lots of fields.

推荐答案

这应该有效。

Vue.directive('init', {
  bind: function(el, binding, vnode) {
    let component = el.__vue__
    component[binding.arg] = binding.value
  }
});

Vue.component('test', {
  template: '<p>{{date}}</p>',
  data() {
    return {
      date: ""
    }
  }
})

new Vue({
  el: '#app'
})

<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.4.1/vue.js"></script>


<div id="app">
  <test v-init:date="'2017-07-20 09:11:42'"></test>
</div>

这篇关于Vue.js在组件外部设置数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆