<div id="app">
<h2>{{message}}h2>
div>
<script>
const vm = new Vue({
el: "#app",
data: {
message: "hello world!",
}
})
script>
<body>
<div id="app">
<h2>{{message}}h2>
<h3>{{movies}}h3>
<ul>
<li v-for="item in movies">{{item}}li>
ul>
div>
body>
<script>
const vm = new Vue({
el: "#app",
data: {
message: "hello world!",
movies: ['柯南', '星际穿越', '大话西游', '盗梦空间']
}
})
script>
<body>
<div id="app">
<h2>当前计数: {{counter}}h2>
<button v-on:click="add">+button>
<button @click="sub">-button>
div>
body>
<script>
const vm = new Vue({
el: "#app",
data: {
counter: 0
},
methods: {
add: function() {
console.log("add ++");
this.counter++;
},
sub: function() {
console.log("sub --");
this.counter--;
}
}
})
script>
<script>
const obj = {
counter: 0
}
const vm = new Vue({
el: "#app",
data: obj,
methods: {
add: function() {
console.log("add ++");
this.counter++;
},
sub: function() {
console.log("sub --");
this.counter--;
}
}
})
script>
MVVM: Model View ViewModel
Model <=> ViewModel <=> View
Model >> JavaScript: Objects(data)
View >> DOM
ViewModel >> Vue
// 1
el: "#app"
// 2
el: document.querySelector("#app")
// 也可以写成,两者都可以,但前者更简洁
可以定义多个函数
在JS中有老师解释说, 在类或对象中定义的叫方法,其它的叫函数,这个观点对于我C++过来的人不赞成这个观点
待补
mustache不仅可以直接写变量, 也可以直接写简单的表达式
<div id="app">
<h2>{{message}}h2>
<h2>{{message}}, 李银河!h2>
<h2>{{firstname + lastname}}h2>
<h2>{{firstname + ' ' + lastname}}h2>
<h2>{{firstname}} {{lastname}}h2>
<h2>{{counter * 2}}h2>
div>
<script src="js/vue.js">script>
<script>
const vm = new Vue({
el: "#app",
data: {
message: "你好啊",
firstname: "Kobe",
lastname: "bryant",
counter: 100
}
})
script>
如果表达式太长,可以移到 Vue的计算属性 computed: 中计算,如下例:
<div id="app">
<p>原始字符串: {{ message }}p>
<p>计算后反转字符串: {{ reversedMessage }}p>
div>
<script>
var vm = new Vue({
el: '#app',
data: {
message: 'Runoob!'
},
computed: {
// 计算属性的 getter
reversedMessage: function () {
// `this` 指向 vm 实例
return this.message.split('').reverse().join('')
}
}
})
script>