vue.js为2.x版本。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="../vue.js"></script>
<style>
.static {
width: 100px;
height: 100px;
border: black 1px solid;
}
.active {
background-color: aquamarine;
}
.text-danger {
border: solid 1px red;
}
</style>
</head>
<body>
<div id="app">
<p>{{msg}}</p>
<p v-if="seen">v-if 文本</p>
<p>v-for:</p>
<ol>
<li v-for="todo in todos">
{{ todo.text }}
</li>
</ol>
<p>v-on:click</p>
<p>{{ message }}</p>
<button v-on:click="reverseMessage">反转消息</button>
<p>v-model:表单双向绑定</p>
<input v-model="message">
<hr>
<p>组件:</p>
<!--
现在我们为每个 todo-item 提供 todo 对象
todo 对象是变量,即其内容可以是动态的。
我们也需要为每个组件提供一个“key”,稍后再
作详细解释。
-->
<todo-item v-for="item in groceryList" v-bind:todo="item" v-bind:key="item.id"></todo-item>
<hr>
<p>样式绑定:</p>
<div class="static" v-bind:class="{ active: isActive, 'text-danger': hasError }"></div>
<p>样式绑定2</p>
<div class="static" v-bind:class="classObject"></div>
<p>样式绑定3:数组绑定</p>
<div class="static" v-bind:class="[activeClass, errorClass]"></div>
<p>样式绑定3:条件切换</p>
<div class="static" v-bind:class="[isActive ? activeClass : '', errorClass]"></div>
<p>样式绑定4</p>
<div class="static" v-bind:class="[{ active: isActive }, errorClass]"></div>
<hr>
<div>
<button-counter></button-counter>
<button-counter></button-counter>
<button-counter></button-counter>
</div>
</div>
<script>
//组件
Vue.component('todo-item', {
// todo-item 组件现在接受一个
// "prop",类似于一个自定义 attribute。
// 这个 prop 名为 todo。
props: ['todo'],
template: '<li>{{ todo.text }}</li>'
})
// 定义一个名为 button-counter 的新组件
Vue.component('button-counter', {
//data是一个函数,保证每个组件独立
data: function () {
return {
count: 0
}
},
template: '<button v-on:click="count++">You clicked me {{ count }} times.</button>'
})
const vm = new Vue({
el: '#app',
data: {
msg: '绑定文本',
seen: true,
todos: [{
text: '学习 JavaScript'
},
{
text: '学习 Vue'
},
{
text: '整个牛项目'
}
],
message: 'Hello Vue.js!',
groceryList: [{
id: 0,
text: '蔬菜'
},
{
id: 1,
text: '奶酪'
},
{
id: 2,
text: '随便其它什么人吃的东西'
}
],
isActive: true,
hasError: false,
error: false,
activeClass: 'active',
errorClass: 'text-danger'
},
computed: {
classObject: function () {
return {
active: this.isActive,
'text-danger': this.error
}
}
},
methods: {
reverseMessage: function () {
this.message = this.message.split('').reverse().join('')
}
}
});
</script>
</body>
</html>