学习Vue子组件操作父组件(emit)


<html lang="zh">
<head>
    <meta charset="UTF-8">
    <title>vue learningtitle>
head>
<body>
    <div id="app">
        <input v-model="count"/>
        <ol>
            
            <todo-item
              v-for="item in groceryList"
              v-bind:todo="item"
              v-bind:key="item.id"
              @do-copy="doCopy"
              @do-add="doAdd"
              @do-sub="doSub"
              >todo-item>
          ol>
    div>

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

<script>
    Vue.component('todo-item', {
        props: ['todo'],
        template: '
  • {{ todo.text }}
  • '
    , methods:{ copy: function(text){ console.log('do-copy',text); this.$emit('do-copy', text) }, add: function() { console.log('do-add'); this.$emit('do-add'); }, sub: function() { console.log('do-sub'); this.$emit('do-sub'); }, }, }) var app = new Vue({ el: '#app', data: { count: 0, groceryList: [ { id: 0, text: '蔬菜' }, { id: 1, text: '奶酪' }, { id: 2, text: '随便其它什么人吃的东西' } ] }, methods:{ doCopy(text) { console.log('groceryList', text) this.groceryList.push({ id: this.groceryList.length, text: text, }) }, doAdd() { console.log('doAdd', this.count); this.count++; }, doSub() { console.log('doSub', this.count); if (this.count > 0) { this.count--; } }, } })
    script> body> html>

    你可能感兴趣的:(WEB前端)