引用

<!-- 开发环境版本,包含了有帮助的命令行警告 -->
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>

数据

1 变量

<div id="app"> 
   
</div>

var app = new Vue({
  el: '#app',
  data: { 
    message: 'Hello Vue!' 
  } 
})

说明:

  • 在VUE类的data属性中定义变量message
  • 在html中,通过{{}}引用

2 属性

<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>
var app2 = new Vue({
  el: '#app-2',
  data: {
    message: 'You loaded this page on ' + new Date()
  }
})

说明:

  • v-bind 是绑定指令
  • 将元素 title 属性和 message 绑定

控制

1 条件

<div id="app-3"> 
  <p v-if="seen">Now you see me</p > 
</div>
var app3 = new Vue({ 
  el: '#app-3', 
  data: { seen: true } 
})

说明:

  • v-if 条件控制命令
  • see VUE的变量

2 循环

<div id="app-4">
  <ol> 
    <li v-for="todo in todos">  </li> 
  </ol>
</div>
var app4 = new Vue({ 
  el: '#app-4', 
  data: { 
    todos: [ 
      { text: 'Learn JavaScript' }, 
      { text: 'Learn Vue' }, 
      { text: 'Build something awesome' } 
    ] 
  }
})

说明:

  • v-for 循环控制命令
  • todos VUE的变量

事件

1 事件监听

<div id="app-5">
  <p></p>
  <button v-on:click="reverseMessage">逆转消息</button>
</div>
var app5 = new Vue({
  el: '#app-5',
  data: {
    message: 'Hello Vue.js!'
  },
  methods: {
    reverseMessage: function () {
      this.message = this.message.split('').reverse().join('')
    }
  }
})

说明

  • v-on 事件绑定
  • reverseMessage 响应函数

2 状态监听

<div id="app-6">
  <p></p>
  <input v-model="message">
</div>
var app6 = new Vue({
  el: '#app-6',
  data: {
    message: 'Hello Vue!'
  }
})

说明:

  • v-model 状态变量绑定
  • message 输入变量

组件

定义

Vue.component('button-counter', {
  data: function () {
    return { count: 0 }
  },
  template: 
  '<button v-on:click="count++">You clicked me 8 times.</button>'
})

数据传递

通过 prop 向子组件传递数据

<blog-post title="My journey with Vue"></blog-post>
<blog-post title="Blogging with Vue"></blog-post>
<blog-post title="Why Vue is so fun"></blog-post>

Vue.component('blog-post', {
  props: ['title'],
  template: '<h3></h3>'
})

说明:

  • 组件定义的属性 props:[‘title’]
  • 引用组件中的属性 title