Vue.js is a very popular JavaScript MVVM library. It is built with data-driven and component-based ideas. Compared with Angular.js, Vue.js provides a simpler and easier-to-understand API, allowing us to quickly get started and use Vue.js. The following article mainly introduces you to the relevant summary of the use of vue.js. Friends in need can refer to it.
1. Vue.js component
vue.js build component usage
Vue.component('componentName',{ /*component*/ });
Note here, the component must be registered first before use, that is to say:
Vue.component('mine',{ template:'#mineTpl', props:['name','title','city','content'] }); var v=new Vue({ el:'#vueInstance', data:{ name:'zhang', title:'this is title', city:'Beijing', content:'these are some desc about Blog' } });
If it is reversed, an error will be reported, because it means that the component is used first, but the component is not registered.
After webpack reports an error, use webpack --display-error-details to troubleshoot
2. Instruction keep-alive
As you can see when watching the demo In vue-router, keep-alive is written, and the meaning of keep-alive is:
If you keep the switched component in memory, you can retain its state or avoid re-rendering. For this purpose, you can add a keep-alive directive
<component :is='curremtView' keep-alive></component>
3. How to make css only work in the current component
In each vue component, you can define its own css. js, if you want the css written in the component to only affect the current component, you only need to write scoped in the style, that is:
<style scoped></style>
4. vuejs inserts images in a loop
in When writing a loop, write the following code:
<p class="bio-slide" v-for="item in items"> <img src="{{item.image}}"> </p>
At this time, a warning will appear on the console
[Vue Warn]: src="{{item.image}}": interpolation in "src" attribute will cause a 404 request. Use v-bind:src instead. This means that interpolating the "src" attribute will cause a 404 request. Use v-bind:src instead.
So replace it with the following:
<p class="bio-slide" v-for="item in items"> <img v-bind:src="item.image"> </p>
It needs to be important here, v-bind can no longer use {{}} when writing, according to the official statement:
<a v-bind:href="url" rel="external nofollow" ></a>
Here href is a parameter, which tells the v-bind directive to bind the href attribute of the element to the value of the expression url. You may have noticed that you can achieve the same result with feature interpolation href="{{url}}" rel="external nofollow" : this is correct, and internally feature interpolation actually converts to v-bind binding.
5. Bind value to a dynamic attribute of the Vue instance
For radio buttons, check boxes and selection box options, the value bound to v-model is usually Static string (logical value for check box):
<!-- `toggle` 为 true 或 false --> <input type="checkbox" v-model="toggle">
But sometimes you want to bind the value to a dynamic attribute of the vue instance. In this case, you can use v-bind to implement it, and the value of this attribute Can not be a string. For example, bind the value of Checkbox to a dynamic attribute of the vue instance:
<input type="checkbox" v-model="toggle" v-bind:true-value="a" v-bind:false-value="b"> <p>{{toggle}}</p>
After binding here, it does not mean that you can switch from true and false to a and b after clicking, because it is defined here The dynamic a and b are a and b on the scope and cannot be displayed directly. At this time,
//当选中时 vm.toggle === vm.a //当没选中时 vm.toggle === vm.b
, so you need to define a and b in the data at this time, that is:
new Vue({ el:'...', data:{ a:'a', b:'b' } });
Six , Fragment instance
The following situations will turn the instance into a fragment instance:
The template contains multiple top-level elements.
The template contains only normal text.
The template only contains other components (other components may be a fragment instance).
The template contains only one element directive, such as
The template root node has a flow control directive, such as v-if or v-for.
These cases result in instances with an unknown number of top-level elements, which will treat its DOM contents as fragments. Fragment instances will still render content correctly. However, it does not have a root node, and its $el points to an anchor node, which is an empty text node (a comment node in development mode).
But more importantly, non-flow control directives, non-prop attributes and transitions on component elements will be ignored because there is no root element for binding:
<!-- 不可以,因为没有根元素 --> <example v-show="ok" transition="fade"></example> <!-- props 可以 --> <example :prop="someData"></example> <!-- 流程控制可以,但是不能有过渡 --> <example v-if="ok"></example>
Fragment instance It has its uses, but usually it is better for the component to have a root node, which will ensure that the instructions and properties on the component elements can be converted correctly, and the performance will be slightly better.
7. Route nesting
Route nesting will render other components into the component instead of jumping the entire page. router-view itself will render the component into the component. Location, if you want to jump to the page, you must render the page to the root component. When configuring the route, write:
var App = Vue.extend({ root }); router.start(App,'#app');
Here, first register the root component to use it to configure the route. Each page is rendered, and then the root component is mounted on the element matching #app.
8. Implement multiple methods of displaying different text according to different conditions
v-if, v-else can realize conditional selection, but if it is multiple continuous conditional selection, You need to use the calculated attribute computed. For example, the string 'empty' is displayed when nothing is written in the input box, otherwise the content in the input box is displayed. The code is as follows:
<p id="test"> <input type="text" v-model="inputValue"> <h1>{{changeVaule}}</h1> </p> new Vue({ el:'#test', data:{ changeVaule:'123' }, computed :{ changeVaule:function(){ if(this.inputValue!==''){ return this.inputValue; }else{ return 'empty'; } } } });
9. Vuejs change detection problem
1. Detect arrays
Due to the limitations of javascript, vuejs cannot detect changes in the following arrays:
Direct index setting elements, such as vm.item[0]={};
Modify the length of data, such as vm.item.length.
In order to solve problem 1, Vuejs extends the observation array and adds a $set() method to it:
// 与 `example1.items[0] = ...` 相同,但是能触发视图更新 example1.items.$set(0, { childMsg: 'Changed!'})
问题2,需要一个空数组替换items。
除了$set() ,vuejs也为观察数组添加了$remove()方法,用于从目标数组中查找并删除元素,在内部调用了splice() 。
因此,不必:
var index = this.items.indexOf(item) if (index !== -1) { this.items.splice(index, 1) }
只需:
this.items.$remove(item);
2.检测对象
受ES5的显示,Vuejs不能检测到对象属性的添加或删除。因为Vuejs在初始化时候将属性转化为getter/setter,所以属性必须在data对象才能让Vuejs转换它,才能让它是响应的,例如:
var data = { a: 1 } var vm = new Vue({ data: data }) // `vm.a` 和 `data.a` 现在是响应的 vm.b = 2 // `vm.b` 不是响应的 data.b = 2 // `data.b` 不是响应的
不过,有办法在实例创建之后添加属性并且让它是响应的。对于Vue实例,可以使用$set(key,value)实例方法:
vm.$set('b', 2) // `vm.b` 和 `data.b` 现在是响应的
对于普通数据对象,可以使用全局方法Vue.set(object, key, value) :
Vue.set(data, 'c', 3) // `vm.c` 和 `data.c` 现在是响应的
有时你想向已有对象上添加一些属性,例如使用 Object.assign() 或 _.extend() 添加属性。但是,添加到对象上的新属性不会触发更新。这时可以创建一个新的对象,包含原对象的属性和新的属性:
// 不使用 `Object.assign(this.someObject, { a: 1, b: 2 })` this.someObject = Object.assign({}, this.someObject, { a: 1, b: 2 })
十、关于vuejs页面闪烁{{message}}
在vuejs指令中有v-cloak,这个指令保持在元素上直到关联实例结束编译。和CSS规则如[v-cloak]{display:none}一起用时,这个指令可以隐藏未编译的Mustache标签直到实例准备完毕。
用法如下:
[v-cloak]{ display:none; } <p v-cloak>{{message}}</p>
这样
不会显示,直到编译结束
十一、关于在v-for循环时候v-model的使用
有时候需要循环生成input,用v-model绑定后,利用vuejs操作它,此时我们可以在v-model中写一个数组selected[$index] ,这样就可以给不同的input绑定不同的v-model,从而分别操作他们。这个我在demo中的dataBind.vue中用到。
十二、vuejs中过渡动画
在vuejs中,css定义动画:
.zoom-transition{ width:60%; height:auto; position: absolute; left:50%; top:50%; transform: translate(-50%,-50%); -webkit-transition: all .3s ease; transition: all .3s ease; } .zoom-enter, .zoom-leave{ width:150px; height:auto; position: absolute; left:20px; top:20px; transform: translate(0,0); }
其中动画在定的时候要注意上下对应,上面有什么,下面有什么,都要变化的,如果有不变化的,应该抽离出去,作为公共css样式,在上面的css中,如果我只写 transform: translate(-50%,-50%);而不写下面的transform: translate(0,0);则会导致上面的transform: translate(-50%,-50%);被添加到下面,认为这个是不变的。
十三、指令v-el的使用
有时候我们想就像使用jquery那样去访问一个元素,此时就可以使用v-el指令,去给这个元素注册一个索引,方便通过所属实例的$el访问这个元素。
注意
HTML不区分大小写,所以v-el:someEl将转换为全小写。可以用v-el:some-el然后设置this.$el.someEl。
示例
<span v-el:msg>hello</span> <span v-el:other-msg>world</span> this.$els.msg.textContent // -> "hello" this.$els.otherMsg.textContent // -> "world" this.$els.msg //-><span>hello</span>
十四、关于vuejs中使用事件名
在vuejs中,我们经常要绑定一些事件,有时候给DOM元素绑定,有时候给组件绑定。绑定事件在HTML中用v-on:click-"event" ,这时evet的名字不要出现大写,因为在1.x中不区分大小写,所以如果我们在HTML写v-on:click="myEvent"而在js中写myEvent就出错误,所以在vuejs的1.x绑定事件时候,要尽量避免使用大写字母。在2.0中没有该限制!
十五、v-if与v-show的区别
v-if直接不渲染这个DOM元素,而v-show是会渲染DOM元素,只是使用display:none隐藏,打开开发者工具可以看到该DOM
十六、关于transition全局钩子如何在组件中使用
Vue.transition是定义一个全局transition钩子的,如果想针对组件定义,则需要如下写法:
export default{ transition:{ 'fade':{ enter() {}, leave() {} } } }
这样fade这个过度钩子只会作用于组件内,如果同时有同名的全局钩子,则会优先使用组建定义的
十七、利用vue-router如何实现组件在渲染出来前执行某个事件
export default{ data(){ return{ selected:0, currentView:'view_0' } }, methods:{ choose(index) { this.selected=index; this.currentView='view_'+index; } }, route:{ data() { /*每次切换路由,在渲染出页面前都会执行*/ } } }
更多超全面的vue.js使用总结相关文章请关注PHP中文网!
相关文章: