Vue学习03

【条件渲染】


--html

<h1 v-if="Math.random()>0.5">Now you see me</h1>
<h1 v-else>Now you don't</h1>

# v-else-if

--html

<div v-if="type==='A'">
  A
</div>
<div v-else-if="type==='B'">
  B
</div>
<div v-else-if="type==='C'">
  C
</div>
<div v-else>
  Not A/B/C
</div>

 

【列表渲染】


v-for 使用数组渲染列表
--html

<ul id=example-1">
  <li v-for="item in items" :key="item.message">
    {{item.message}}
  </li>
</ul>

-- js

var example1=new Vue({
  el:'#example-1',
  data:{
    item:[
      {message:'Foo'},
      {message:'Bar'}
    ]
  }
})

--view

  • Foo
  • Bar

# 在 v-for 里使用对象
-- html

<ul id='v-for-object' class='demo'>
  <li v-for="value in object">
    {{value}}
  </li>
</ul>

-- js

new Vue({
el:'#v-for-object',
  data:{
    object:{
      title:'How to do lists in Vue',
      author:'Jane Doe',
      publishedAt:'2016-04-10'
    }
  }
})

--view

  •  How to do lists in Vue
  •  Jane Done
  •  2016-04-10

使用第二个参数为property名称:
--html

<div v-for="(value,name) in object">
  {{name}}:{{value}}
</div>

-- view

title:How to do lists in Vue
author:Jane Doe
publishedAt:2016-04-10

加上索引的三个参数:

--html

<div v-for="(value,name,index) in object">
  {{index}}.{{name}}:{{value}}
</div>

--view

0.title:How to do lists in Vue
1.author:Jane Doe
2.publishedAt:2016-04-10

 

#在组件上使用 v-for
--html

<div id="todo-list-example">
<form v-on:submit.privent="addNewTodo">
  <label for="new-todo">Add a todo</label>
  <input
    v-model="newTodoText"
    id="new-todo"
    placeholder="E.g. Feed the cat">
  <button>Add</button>
</form>
<ul>
  <li
    is="todo-item"
    v-for="(todo,index)in todos"
    v-bind:key="todo.id"
    v-bind:title="todo.title"
    v-on:remove="todos.splice(index,1)">
  </li>
</ul>
</div>

--js

Vue.comonent('todo-item',{
template:'\
  <li>\
  {{title}}\
  <button v-on:click="#emit(\'remove\'">Remove</button>\
  ',
props:['title']
})

new Vue({
  el:'#todo-list_example',
  data:{
    newTodoText:'',
    todos:[
  {
  id:1,
  title:'Do this dishes'
},
{
  id:2,
  title:'Take out the trash'
}
],
  nextTotoId:3
},
methods:{
  addNewTodo:function(){
    this.todos.push({
      id:thisnextTotoId++,
      title:this.newTodoText,
})
  this.newTodoText=''
    }
  }
})

 

【监听事件】


v-on 指令用于监听DOM事件
--html

<div id="example-1">
<button v-on:click='greet'>Greet</button>
</div>

-- js

var example1=new Vue({
  el:'#example-2',
  data:{
    name:'Vue.js'
},
methods:{
  greet:function(event){
    alert('Hello '+this.name+'!')
  if(event){
    alert(event.target.tagName)
      }
   }
  }
})

# 内联调用

--html

<div id='example-3">
<button v-on:click="say('hi')">Say hi</button>
<button v-on:click="say('waht')">Say what</button>
</div>

--js

new Vue({
    el:"#example-3",
    methods:{
    say:function(message){
        alert(message)
        }    
    }
})        

 

posted @ 2021-04-27 17:39  那些你未完成的梦  阅读(61)  评论(0编辑  收藏  举报