Vue.js学习笔记--1.基础HTML和JS属性的使用

 

整理自官网教程 -- https://cn.vuejs.org/

 

1. 在HTML文件底部引入Vue  

<script src="https://cdn.jsdelivr.net/npm/vue"></script>

2. 基础HTML标签和属性

<div id="app">
    <!--v-bind:title 可缩写为 :title -->
    <!--添加v-once属性时,能执行一次性地插值 -->
    <!-- v-html="xx"可插入HTML代码 -->
    <span v-bind:title="info">
    <!-- 支持JS单个表达式,不能访问用户定义的全局变量 -->
         {{ message }}  
    </span> 
    <!--v-on:click 可缩写为 @click -->       
    <button v-on:click="reverseMessage">逆转消息</button>
    <p>Computed reversed message: "{{ reversedMessage }}"</p>
    <p v-if="seen">切换元素显示</p>
    <ol>
        <li v-for="todo in todos">
          {{ todo.text }}
        </li>
    </ol>
  <!-- v-model实现表单输入和后台状态之间的双向绑定 -->
  <input v-model="message">    
</div>

 

 3. 基础JS属性

var app = new Vue({
    el:'#app',
    data:{    //预设在data内的属性才是响应式的
      message:'Hello Vue!',
      info:'Show title.',
      seen:true,
      todos: [
          { text: 'Learn JavaScript' },
          { text: 'Learn Vue' },
          { text: 'Build something awesome' }
        ],
      question: '',
      answer: 'I cannot give you an answer until you ask a question!'
   },
  methods: {    //Vue实例内方法函数
      reverseMessage: function () {
        this.message = this.message.split('').reverse().join('')
      }
   },
  computed: {    //计算属性,基于其依赖进行缓存,依赖变化时才重新求值
    reversedMessage: function() {      //默认方法为reversedMessage的getter(),也可设置setter()方法
        return this.message.split('').reverse().join('')
      }
   },
  watch: {    //侦听属性,适合在数据变化时需要执行异步或开销较大时
    // 如果 `question` 发生改变,这个函数就会运行
     question: function (newQuestion, oldQuestion) {
         this.answer = 'Waiting for you to stop typing...'
      //调用其它处理答案的方法
     }
   },  
  created: function () {    //vue实例中生命周期钩子函数之一
    console.log('tips is:' + this.tips)
  }
})

 4. 备注

  a. Vue实例中带有前缀$的属性和方法可将其与用户定义的分开,如$data,$watch等。

  b. 利用freeze()函数可阻止修改现有data,用法如下:    

var obj = {
  foo: 'bar'
}
Object.freeze(obj);
//...
//vue实例中设置
//...
data: {
    obj
}

 

posted on 2018-03-15 09:42  FreshCoder_xq  阅读(266)  评论(0)    收藏  举报

导航