从头开始学Vue

模版语法

不管是使用v-指令绑定attribute还是Mustache语法,后面可以跟值或者js表达式,如果是事件监听后面可以跟函数或js语句,例如:


...
{{ message.split('').reverse().join('') }}


动态属性

上面说的是值是动态的,从2.6.0开始,新增属性动态

 ... 
 ... 
 ... 

Class和Style绑定

Class对象语法

data: { classObject: { active: true, 'text-danger': false } }
computed: { classObject: function () { return { active: this.isActive && !this.error, 'text-danger': this.error && this.error.type === 'fatal' } } }
// 用于自定义组件

Class数组语法

data: { activeClass: 'active', errorClass: 'text-danger' }

通过以上例子我们总结出如果是对象,那么变量必须是布尔值,如果是数组,那么变量必须是值或js表达式。

Style对象语法

data: { activeColor: 'red', fontSize: 30 }
data: { styleObject: { color: 'red', fontSize: '13px' } }

Style数组语法

data () { return { baseStyles: { color: 'red' }, overridingStyles: { fontSize: '70px' } } }

从上面我们可以看到如果是对象,变量就是值或js表达式,如果是数组内部对象的变量同样是值或js表达式。

列表渲染

  • {{ parentMessage }} - {{ index }} - {{ item.message }}
data: { parentMessage: 'Parent', items: [ { message: 'Foo' }, { message: 'Bar' } ] }
  • {{ parentMessage }} - {{ index }} - {{ item.message }}
data: { parentMessage: 'Parent', items: [ { message: 'Foo' }, { message: 'Bar' } ] }
{{ index }}. {{ name }}: {{ value }}
data: { object: { title: 'How to do lists in Vue', author: 'Jane Doe', publishedAt: '2016-04-10' } }

从上面例子中我们可以看出v-for可以遍历数组也可以遍历对象,遍历数组最多两个参数,遍历对象可以有三个参数,in和of遍历效果一样,只不过of更接近js迭代器语法。v-for的变量只能是值或js表达式,比如从计算属性、方法里面返回的值,也可以是整数例如v-for="n in 10"