Vue设计模式理解
1.什么是Vue
Vue (读音 /vjuː/,类似于 view) 是一套用于构建用户界面的渐进式框架。与其它大型框架不同的是, Vue 被设计为可以自底向上逐层应用。Vue 的核心库只关注视图层,不仅易于上手,还便于与第三方库 或既有项目整合。另一方面,当与现代化的工具链以及各种支持类库结合使用时,Vue 也完全能够为复 杂的单页应用提供驱动。 ==come from baidu.com
2.第一个Vue程序
1.安装vue并将vue.js放在lib目录下
npm intall vue
工程目录如下
2.编写视图层 (使用vue的插值表达式 {{data中的变量}})
<div id="app">
{{message}}
</div>
3.编写Vue对象
<script src="../lib/vue.js"></script>
<script>
// ViewModel Vue对象
var vm = new Vue({
// 1、 绑定前端页面 和 jQuery绑定是一样的!
el: '#app',
// 2、连接后台数据! Model
data: {
// 未来的开发,这里的值是从后端进行获取的!
message: 'hello,vue!'
}
})
</script>
4.提供数据!
message: 'hello,vue!'
3.结合MVVM模式理解
4.Vue指令详解
v-bind 绑定视图
<body>
<div id="app">
<!-- 通过v-bind绑定vm中的data -->
<p v-bind:title="message">Try it here</p>
<!-- v-bind可以简写为: -->
<p :title="message">Try it here again</p>
</div>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script>
new Vue({
el:'#app',
data:{
message:'time:' + new Date().toLocaleDateString()
}
})
</script>
</body>
v-if 判断
<body>
<div id="app">
<!-- -->
<p v-if="type==='A'">This is type A</p>
<p v-else-if="type==='B'">This is type B</p>
<p v-else-if="type==='C'">This is type C</p>
<p v-else>This is type D</p>
</div>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script>
new Vue({
el:'#app',
data:{
type:'B'
}
})
</script>
</body>
v-for 循环
<body>
<div id="app">
<!-- -->
<li v-for="item in items">
{{item.message}}
</li>
</div>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script>
new Vue({
el:'#app',
data:{
items:[
{message:'This is the first'},
{message:'This is the second'},
{message:'This is the third'},
{message:'This is the fourth'},
]
}
})
</script>
</body>
v-on 事件
<body>
<div id="app">
<!-- -->
<button v-on:click="sayHi">click here!</button>
<!-- v-on可以简写为@ -->
<button @click="sayHi">click here new!</button>
</div>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script>
var vm = new Vue({
el:'#app',
data:{
message:'Test the v-bond method'
},
//所有的方法都放在methods,可以通过v-on指定调用
methods:{
sayHi:function(){
alert(this.message)
}
}
})
</script>
</body>
v-model 双向绑定
<body>
<div id="app">
<!-- -->
<input type="text" v-bind:value="message">
<!-- v-model实现双向绑定view和model的数据实现互通-->
<input type="text" v-model:value="message">
</div>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script>
var vm = new Vue({
el:'#app',
data:{
message:'Test the v-model'
}
})
</script>
</body>