Im using vuejs and some time i need to create new variables in the template.
In angular I could go:
<div ng-app="" ng-init="myText='Hello World!'">
<h1>{{myText}}</h1>
How can that be achived in vuejs?
Thanks!
Reactive model — Vue's reactive model is very similar to that of AngularJS, which allows AngularJS developers to adopt the mental model of Vue much faster than comparative frameworks and libraries.
Since Angular supports using custom Web Components, you'll be able to use the Vue components (wrapped as Web Components).
Using the v-if , v-else , and v-else-if Directives. Vue. js comes pre-packaged with a number of directives that developers commonly use when working within the framework. Directives such as v-if , v-show , v-on , v-model , v-bind , v-html , and more are all provided for you out-of-the-box.
js is a library for building interactive web interfaces. Technically, Vue. js is focused on the ViewModel layer of the MVVM pattern. It connects the View and the Model via two way data bindings.
It's not really recommended to init from the template, but it is possible to do this with a directive:
Vue.directive('init', {
bind: function(el, binding, vnode) {
vnode.context[binding.arg] = binding.value;
}
});
Which you can use like:
<div v-init:myvar="'foo'"></div>
All that does is take the binding argument
(this bit after the :
) and sets it's value the the binding value
on the Vue instance's data property.
Here's the JSFiddle: http://jsfiddle.net/craig_h_411/snpLtt8c/
A couple of caveats for that though, firstly binding.arg
is always passed as lower case, so if you want to use camelCase variables you will probably need to implement something that converts kebab-case to camelCase:
Vue.directive('init', {
bind: function(el, binding, vnode) {
// convert kebab-case to camelCase
let arg = binding.arg.split('-').map((arg, index) => {
return (index > 0) ? arg[0].toUpperCase() + arg.substring(1) : arg;
}).join('');
vnode.context[arg] = binding.value;
}
});
Markup
<div v-init:my-text="'Hello World'"></div>
Here's the Fiddle for that: http://jsfiddle.net/craig_h_411/9xepfpw3/
Secondly, you still need to declare your variables upfront in data
.
For the ones that wanted the same functionality but instead of initializing a data property, it calls a function/method on your Vue instance which may, in turn, assign values or call an API, check this out.
v-init directive
Vue.directive('init', {
bind: function (el, binding, vnode) {
vnode.context[binding.expression]();
}
});
Sample Vue instance
new Vue({
el: '#some-element',
methods: {
callApi: function () {
// add your http api call here --.
}
}
});
Usage in Html
<div id="some-element" v-init="callApi"></div>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With