Vue js使用es6语法来实现组件

版权声明:本文为博主总结文章,未经博主允许您依然可以转载。 https://blog.csdn.net/Memery_last/article/details/60874985

鉴于官方的文档是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: 300px;
    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

猜你喜欢

转载自blog.csdn.net/Memery_last/article/details/60874985