近期项目的前端页面准备引入Vue.js,看了网上一些简介,及它和JQuery的对比,发现对于新入门的前端开发来说,Vue 其实也是比较适用的一个框架,其实用性不比JQuery差,感觉还挺有意思,于是研究了
一下其基本用法,下面是整理出来的学习例子(有官网上的,也有自己消化以后整理的),希望对大家有参考价值。
<html>
<head>
<title>Vue test</title>
</head> <body> <div id="app">
<p>{{ message }}</p>
</div> <div id="app-2">
<span v-bind:title="message">
Hover your mouse over me for a few seconds to see my dynamically bound title!
</span>
</div> <div id="app-3">
<p v-if="seen">Now you see me</p>
</div> <div id="app-4">
<ol>
<li v-for="todo in todos">
{{ todo.text }}
</li>
</ol>
</div> <div id="app-4_2">
<ul>
<li v-for="todo in todos">
{{ todo }}
</li>
</ul>
</div> <div id="app-5">
<p>{{ message }}</p>
<button v-on:click='reverseMessage'>reverse button</button>
</div> <div id="app-6">
<p>{{ message }}</p>
<input v-model='message'>
</div> <div id="app-7">
<ol>
<!-- Now we provide each todo-item with the todo object -->
<!-- it's representing, so that its content can be dynamic -->
<todo-item v-for="item in groceryList" v-bind:todo="item"></todo-item>
</ol>
</div>
<div id="app-7_2">
<ul>
<todo-text v-for="item in textInfoList" v-bind:todo="item"></todo-text>
</ul>
</div> <script src="./vue.min.js"></script>
<script> // 静态数据绑定
var app = new Vue({
el: '#app',
data: {
message: 'Hello Vue!'
}
}) // 动态属性值绑定
var app2 = new Vue({
el: '#app-2',
data: {
message: 'You loaded this page on ' + new Date()
}
}) // 控制标签是否显示
var app3 = new Vue({
el: '#app-3',
data: {
seen: true
}
}) // 遍历对象数组
var app4 = new Vue({
el: '#app-4',
data: {
todos: [
{ text: 'Learn JavaScript' },
{ text: 'Learn Vue' },
{ text: 'Build something awesome' }
]
}
})
// 直接遍历数组
var app4_2 = new Vue({
el: '#app-4_2',
data: {
todos: [
'Learn JavaScript',
'Learn Vue',
'Build something awesome'
]
}
}) // 绑定一个逆排字符串的函数
var app5 = new Vue({
el: '#app-5',
data: {
message: 'Hello Vue.js.'
},
methods: {
reverseMessage: function() {
this.message = this.message.split('').reverse().join('')
}
}
}) // 同步用户输入
var app6 = new Vue({
el: '#app-6',
data: {
message: 'test text input.'
}
}) // 动态绑定数据到模板中的变量
Vue.component('todo-item', {
props: ['todo'],
template: '<li>{{ todo.text }}</li>'
})
var app7 = new Vue({
el: '#app-7',
data: {
groceryList: [
{ text: 'Vegetables' },
{ text: 'Cheese' },
{ text: 'Whatever else humans are supposed to eat' }
]
}
}) // 注意参数名 todo 及其类型 ['todo'] 都不能变
Vue.component('todo-text', {
props: ['todo'],
template: '<li>{{ todo.line }} - {{ todo.text }}</li>'
})
var app7_2 = new Vue({
el: '#app-7_2',
data: {
textInfoList: [
{
line: 'line one.' ,
text: 'textInfo'
},
{
line: 'line two.' ,
text: 'textInfo'
},
{
line: 'line three.' ,
text: 'textInfo'
}
]
}
}) </script> </body> </html>