vue截取html需要渲染的一部分来进行实时渲染操作,代替原来的html渲染完成后通过js来修改dom节点,效率更高,更现代化,是前端的进步。
字符串数据渲染:
<div id="app"> my name is {{message}}. </div> <script src="https://unpkg.com/vue"></script> <script> const app = new Vue({ el: '#app', data: { message: 'maoriaty' } }) </script>
数组数据渲染:
<div id="app"> <ul> <li v-for="item in message">{{item}}</li> </ul> </div> <script src="https://unpkg.com/vue"></script> <script> const app = new Vue({ el: '#app', data: { message: ['maoriaty','jabin','susan','jack'] } }) </script>
ajax等数据渲染:
<div id="app"> <ul> <li v-for="item in message">{{item}}</li> </ul> </div> <script src="https://unpkg.com/vue"></script> <script> const app = new Vue({ el: '#app', data: { message: [] }, created () { fetch('http://maoriaty.top/myjson/name') //model: cors默认权限跨域访问,需要服务端开启允许跨域访问,no-cors为无权限跨域访问,能拿到数据但不能使用 .then(Response => Response.json()) .then(data => this.message = data.names) } }) </script>
计算属性:
<div id="app"> <ul> <li v-for="item in message"> {{item.age}} {{item.name}} <span v-if='item.age === 2'>- IS GOOD AT ENGLISH.</span> <button @click='item.age += 1'>Add</button> </li> </ul> <h2>Total Inventory: {{totalNums}}</h2> </div> <script src="https://unpkg.com/vue"></script> <script> const app = new Vue({ el: '#app', data: { message: [] }, computed: { totalNums () { return this.message.reduce((sum, person) => { return sum + person.age },0) } }, created () { fetch('http://maoriaty.top/myjson/name') //model: cors默认权限跨域访问,需要服务端开启允许跨域访问,no-cors为无权限跨域访问,能拿到数据但不能使用 .then(Response => Response.json()) .then(data => this.message = data.names) } }) </script>
表单数据绑定:
<div id="app"> <ul> <li v-for="item in message"> <input type="number" v-model.number='item.age'> {{item.name}} <span v-if='item.age === 2'>- IS GOOD AT ENGLISH.</span> <button @click='item.age += 1'>Add</button> </li> </ul> <h2>Total Inventory: {{totalNums}}</h2> </div> <script src="https://unpkg.com/vue"></script> <script> const app = new Vue({ el: '#app', data: { message: [] }, computed: { totalNums () { return this.message.reduce((sum,person) => { return sum + person.age },0) } }, created () { fetch('http://maoriaty.top/myjson/name') //model: cors默认权限跨域访问,需要服务端开启允许跨域访问,no-cors为无权限跨域访问,能拿到数据但不能使用 .then(Response => Response.json()) .then(data => this.message = data.names) } }) </script>