Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vue.js set data outside component

Tags:

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?

I was thinking about something like this:

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

But it's not working:

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?

--edit--

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

like image 699
Jenssen Avatar asked Jul 20 '17 10:07

Jenssen


1 Answers

This should work.

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>
like image 104
Ikbel Avatar answered Sep 23 '22 00:09

Ikbel