Maison  >  Article  >  interface Web  >  探索Vue.jscomponent内容实现

探索Vue.jscomponent内容实现

高洛峰
高洛峰original
2017-01-16 13:01:28990parcourir

现在来系统地学习一下Vue(参考vue.js官方文档):

Vue.js是一个构建数据驱动的web界面的库,其目标是实现响应的数据绑定和组合的试图组件。

Vue.js拥抱数据驱动的视图概念,这意味着我们能在普通的HTML模板中使用特殊的用法将DOM“绑定”到底层数据。一旦创建了绑定,DOM将于数据保持同步。

探索Vue.jscomponent内容实现

以下参考代码与上面的模型相对应

<!-- 这是我们的 View -->
<div id="example-1">
   Hello {{ name }}!
</div>
// 这是我们的 Model
var exampleData = {
   name: &#39;Vue.js&#39;
}
  
// 创建一个 Vue 实例或 "ViewModel"
// 它连接 View 与 Model
var exampleVM = new Vue({
   el: &#39;#example-1&#39;,  // 在一个id为&#39;example-1&#39;的实体上挂载
   data: exampleData  // 数据流
})

通常我们会把Model写在Vue实例当中,下面写法与上面写法效果一样:

<!-- 这是我们的 View -->
<div id="example-1">
   Hello {{ name }}!  <!--- Vue的数据模型用{{datamodel}}包裹起来 --->
</div>
  
// 创建一个 Vue 实例或 "ViewModel"
// 它连接 View 与 Model<br><script>
var exampleVM = new Vue({
   el: &#39;#example-1&#39;,  // 在一个id为&#39;example-1&#39;的实体上挂载
   data: {
       name: &#39;Vue.js&#39;
      } // 数据流
})<br></script>

这样一段程序执行后,在#example-1这个控件中就会显示‘Hello Vue.js!'。

下面来看看指令(Directives):
指令是特殊的带有前缀 v- 的特性,指令的值限定为绑定表达式,比如一个if的指令:

cc2ec3a3fb30a3a10b5e1a187a78485chello!e388a4556c0f65e1904146cc1a846bee

还有绑定指令,即将某些属性值与一些值相绑定,比如:

50e218a061b97797724fc7fd7af2c9e1

这里省略了“v-bind”,使得input的属性值赋值具有“计算”的效果。 

计算属性

这里介绍一下$watch的用法,用于当一个数据需要根据其他的数据而变化时的情况:

<script><br>var vm = new Vue({
 el: &#39;#demo&#39;,
 data: {
  firstName: &#39;Foo&#39;,
  lastName: &#39;Bar&#39;,
  fullName: &#39;Foo Bar&#39;
 }
})<br></script>
  
vm.$watch(&#39;firstName&#39;, function (val) { // 当firstname改变时,立马更新vm.fullname
 this.fullName = val + &#39; &#39; + this.lastName
})
  
vm.$watch(&#39;lastName&#39;, function (val) {  // 当lastname改变时,立马更新vm.fullname
 this.fullName = this.firstName + &#39; &#39; + val
})

在这里,所有的数据的对象都可以通过vm.firstname等来访问。   

v-model  

顾名思义,就是Vue当中的数据模型,它用来绑定Vue实例中的数据:

<!--- bi-direction bound --->
<div id="app">
  <p>{{message}}</p>
  <input v-model="message"> <!--Model,input输入的数据会立即反馈到Vue实例中--> 
</div>
<script>
  new Vue({
    el: &#39;#app&#39;,  // View
    data: {
      message: &#39;Hello Vue.js&#39;
    }
  })
</script>

比如要用来绑定一个表单控件,就是把选择的值显示出来:

<!---    表单控件绑定-单选 --->
<div id="myselect">  // 外面这一层我一开始没有加,然后就出错了,el好像一般是挂载在<div>构件上
<select v-model="selected"> // data的数据类型是selected,值是选取的值
  <option seleceted>A</option>
  <option>B</option>
  <option>C</option>
</select>
<span>Selected: {{ selected }}</span>
</div>
  
<script>
  new Vue({
    el: &#39;#myselect&#39;,
    data:{
      selected:[]
    }
  })
</script>

v-if, v-else    

这个指令可以用的很灵活,比如我在表单中生成新题目,有“单选题”、“多选题”、“文本题”三种,那么针对不同的题目应该显示的控件有所不同,这时可以使用如下语法:

<div v-if="questItem.type === &#39;textarea&#39;"> // 注意是三个等号
    <textarea></textarea>
</div>
<div v=else>
    <div></div>
</div>

v-for

这个用于对数组元素的遍历,举个例子: 

<ul id="demo">
  <li
    v-for="item in items"
    class="item-{{$index}}">  <!--- $index指的是当前数组元素在数组中的位置 --->
    {{parentMessage}} - {{$index}} - {{item.message}} <!--一个view结构-->
  </li>
</ul>
<button id="btn1">点击我</button>
<script>
  var demo= new Vue({
    el: &#39;#demo&#39;,
    data:{
      parentMessage: &#39;Parent&#39;,
      items:[
        {message: &#39;Foo&#39;},
        {message: &#39;Bar&#39;}
      ]
    }
  })
</script>

以上代码的意思是遍历demo实例中的items数组,将里面的每一个数组元素('Foo','Bar')分别在25edfb22a4f469ecb59f1190150159c6标签中显示出来

为了避免对整个列表进行渲染,经常会使用:track-by = "$index",表示只对当前数组元素进行操作。  

至此,关于Vue的最基本的东西已经介绍完,需要更多的API资料可以参考: http://cn.vuejs.org/api/ 

Vue文件的结构以及数据流的控制

在vue文件中,我们经常可以看到这样的格式:

<template>
    <div> </div>
</template>
  
<script>
    export default{
       data(){ ...
       },
       methods:{ // 自定义方法,可对data进行处理
          method1(){ ... }
          ...    
       },
       components: { ... }
       vuex: {
          getters:{ // 获取store的数据
            questionnaire: state => state.currentQuestionnaire
          }
          actions: { //用来分发数据容器store中mutations方法
            action1(){ dispatch("SET_QUEST", item) } // dispatch用来调用父组件store的"SET_QUEST"方法
            action2(){ ... }
       }
       directives: {
          &#39;my-directive&#39;: {
            bind: function(){ //钩子函数,只调用一次,在指令第一次绑定到元素上时调用 }
            update: function(newValue, oldValue) { //钩子函数,在bind之后以初始值为参数第一次调用,之后每当绑定至变化时调用 }
            unbind: function(){ //钩子函数,只调用一次,在指令从元素上解绑时调用 }
          }
       } 
          // 自定义指令,在<template>中以<div v-my-directives = ""> 方式调用   
     }
</script>
  
<style>  </style>

d477f9ce7bf77f53fbcf36bec1b69b7a中放置的是这个页面(或者页面的一部分)所拥有的控件,而3f1c4e4b6b16bbbd69b2ee476dc4f83a中定义的是Vue的数据对象和方法,c9ccee2e6ea535a969eb3f532ad9fe89中定义的是控件的css样式。

在methods中经常使用到“this”关键字,该关键字指向Vue组件实例。

event.target: 触发事件的具体控件,不产生冒泡作用,是谁就是谁,这个在锁定事件触发的控件时经常用到,比如:

<div @click.stop = "addItem($event)">
   <span data-type = "radio">单选题</span>
   <span data-type = "checkbox">多选题</span>
   <span data-type = "textarea">文本题</span>
</div>
  
<script>
   export default{
      method: {
          addItem(event){
             let target = event.target
             if(target.nodeName.toLowerCase() === &#39;span&#39;) { // 当点击了选择的按钮后
                this.showMask = true  // 显示弹出框
                this.questItem.type = target.dataset.type  // 设置问题的类型
             }
      }
   }
</script>

最后讲讲this.$els: 一个对象,包含注册有v-el的DOM元素

<div class = "promt-header">
  <div>
     <label> 问题名称: </label>
     <input type = "text", placeholder = "请输入标题" v-el: item-title/>
  </div>
</div>
<div class = "promt-footer" @click.stop = "handleInput(&event)">
   <button type = "button" data-operation = "confirm"> 确定 </button>
   <button type = "button" data-operation = "cancel"> 取消 </button>
</div>
  
<script>
   methods: {
        handleInput(event) {
          let target = event.target
          if(target.nodeName.toLowerCase() !== &#39;button&#39;) {
            return
          }
          let itemTitle = this.$els.itemTitle
          let itemSelections = this.$els.itemSelections
          if(target.dataset.operation === "confirm") {
            if(this.questItem.type === "textarea") {
              this.addTextarea(itemTitle)
            } else {
              this.addSelections(itemTitle, itemSelections)
            }
          } else {
            this.handleCancel()
          }
        },
   }
</script>

上面的代码是不完整的,但是可以看到,v-el把该控件挂载在一个名字为"item-title"的实体中,我们可以通过this.$els.itemTitle将其提取出来

要使用该控件的属性值(输入值),可以这样:

this.$els.itemTitle.value

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持PHP中文网。

更多探索Vue.jscomponent内容实现相关文章请关注PHP中文网!

Déclaration:
Le contenu de cet article est volontairement contribué par les internautes et les droits d'auteur appartiennent à l'auteur original. Ce site n'assume aucune responsabilité légale correspondante. Si vous trouvez un contenu suspecté de plagiat ou de contrefaçon, veuillez contacter admin@php.cn