1. 程式人生 > >Vue js使用es6語法來實現元件

Vue js使用es6語法來實現元件

鑑於官方的文件是es5的,但是使用vue-cli生成的程式碼模板是es6的,而且es6的模組化等也非常方便,以後肯定是主流。

1)定義簡單元件 ItemTemplate.vue

<template>
  <li>{{text}}</li>
</template>

<script>
  export default {
    props: ['text'],
  }
</script>

2)使用元件

<style>
  .test {
    text-align: left;
    width: 300
px; margin-left:auto; margin-right:auto; } </style> <template> <div id="test" class="test"> <h1>Hello {{person.name}}!</h1> 介紹:<input type="text" v-model="person.introduce"/><br/> 年齡:<input type="text" v-model="person.age"/><br/>
TODO:<br/> <li v-for="todo in person.todos"> {{todo.id}}{{todo.text}} </li> <Item text="todo"/> <button v-on:click="buttonClick">點我</button> </div> </template> <script> import Item from './ItemTemplate.vue' export default
{ name: 'test', components: { Item }, data() { return { person: { name: 'VUE', introduce: null, age: null, todos:[ {id:1, text:'任務1'}, {id:2, text:'任務2'}, {id:3, text:'任務3'}, ] } }; }, methods: { buttonClick() { this.person.introduce = 'i am sure'; this.person.age = 20; } } }
</script>

可以參考iView元件庫的原始碼實現來學習:
https://github.com/iview/iview/blob/master/src/components