vue parent child component and ref

Keywords: Javascript Vue JSON Attribute

Pass value from parent component to child component

 <div id="app">
    <! -- when a parent component references a child component, the data that needs to be passed to the child component can be passed to the internal of the child component in the form of attribute binding through the form of attribute binding (v-bind:), which is used by the child component -- >
    <com1 v-bind:parentmsg="msg"></com1>
  </div>
// Create Vue instance to get ViewModel
    var vm = new Vue({
      el: '#app',
      data: {
        msg: '123 ah-Data in parent component'
      },
      methods: {},

      components: {
        // Conclusion: after demonstration, it is found that the data on the data in the parent component and the methods in the methods cannot be accessed by default in the child component
        com1: {
          data() { // Note: the data data in the child component is not passed through the parent component, but is private to the child component itself. For example, the data requested by the child component through Ajax can be put on the data;
            // Data on data is readable and writable;
            return {
              title: '123',
              content: 'qqq'
            }
          },
          template: '<h1 @click="change">This is a subcomponent --- {{ parentmsg }}</h1>',
          // Note: all the data in props in the component is passed to the child component through the parent component
          // The data in props is read-only and cannot be reassigned
          props: ['parentmsg'], // Define the parentmsg property passed from the parent component in the props array first, so that you can use the data. If it is read-only and written, a warning will be given
          directives: {},
          filters: {},
          components: {},
          methods: {
            change() {
              this.parentmsg = 'Has been revised.'
            }
          }
        }
      }
    });

Pass method from parent component to child component

<div id="app">
    <! -- the parent component passes the method to the child component, using the event binding mechanism; v-on, when we customize an event property, then the child component can call the method passed in through some ways -- >
    <com2 @func="show"></com2>
  </div>

  <template id="tmpl">
    <div>
      <h1>This is a subcomponent</h1>
      < input type = "button" value = "this is the button in the child component - click it to trigger the func method passed by the parent component" @ Click = "myclick" >
    </div>
  </template>
 // Defines a component template object of literal type
    var com2 = {
      template: '#tmpl ', / / by specifying an Id, it means to load the content in the template element of the specified Id as the HTML structure of the component
      data() {
        return {
          sonmsg: { name: 'Little son', age: 6 }
        }
      },
      methods: {
        myclick() {
          // When clicking the button of the child component, how to get the func method passed by the parent component and call this method???
          //  Trigger, call and launch
          // this.$emit('func123', 123, 456)
          this.$emit('func', this.sonmsg)
        }
      }
    }


    // Create Vue instance to get ViewModel
    var vm = new Vue({
      el: '#app',
      data: {
        datamsgFormSon: null
      },
      methods: {
        show(data) {
          // console.log('show method on parent component is called: -- '+ data)
          console.log(data);
          this.datamsgFormSon = data
        }
      },

      components: {
        com2
        // com2: com2
      }
    });

vue + local storage for comments

Is it to understand the method from parent component to child component

<div id="app">


    <cmt-box @func="loadComments"></cmt-box>


    <ul class="list-group">
      <li class="list-group-item" v-for="item in list" :key="item.id">
        <span class="badge">Commentator: {{ item.user }}</span>
        {{ item.content }}
      </li>
    </ul>


  </div>


  <template id="tmpl">
    <div>

      <div class="form-group">
        <label>Commentator:</label>
        <input type="text" class="form-control" v-model="user">
      </div>

      <div class="form-group">
        <label>Comments:</label>
        <textarea class="form-control" v-model="content"></textarea>
      </div>

      <div class="form-group">
        <input type="button" value="Comment" class="btn btn-primary" @click="postComment">
      </div>

    </div>
  </template>
var commentBox = {
      data() {
        return {
          user: '',
          content: ''
        }
      },
      template: '#tmpl',
      methods: {
        postComment() { // How to comment
          // Analysis: business logic for comments
          // 1. Where is the comment data stored Stored in localStorage.setItem('cmts', ')
          // 2. Organize the latest comment data object first
          // 3. Find a way to save the comment object obtained in the second step to localStorage:
          //  3.1 localStorage only supports storing string data. Call JSON.stringify first 
          //  3.2 before saving the latest comment data, get the previous comment data (string) from localStorage, convert it into an array object, and then push the latest comment to this array
          //  3.3 if the comment string obtained from localStorage is empty and does not exist, a '[]' can be returned for JSON.parse to convert
          //  3.4, put the latest comment list array again, call JSON.stringify to array string, then call localStorage.setItem().

          var comment = { id: Date.now(), user: this.user, content: this.content }

          // Get all comments from localStorage
          var list = JSON.parse(localStorage.getItem('cmts') || '[]')
          list.unshift(comment)
          // Save the latest comment data again
          localStorage.setItem('cmts', JSON.stringify(list))

          this.user = this.content = ''

          // this.loadComments() // ?????
          this.$emit('func')
        }
      }
    }

    // Create Vue instance to get ViewModel
    var vm = new Vue({
      el: '#app',
      data: {
        list: [
          { id: Date.now(), user: 'Li Bai', content: 'It's natural that I'm useful' },
          { id: Date.now(), user: 'Jiang Xiao Bai', content: 'Persuade you to drink more' },
          { id: Date.now(), user: 'pony', content: 'My name is ma. I see cattle and sheep in the wind' }
        ]
      },
      beforeCreate(){ // Note: the loadComments method cannot be called here, because both data and methods have not been initialized when the hook function is executed

      },
      created(){
        this.loadComments()
      },
      methods: {
        loadComments() { // From local localStorage, load the comment list
          var list = JSON.parse(localStorage.getItem('cmts') || '[]')
          this.list = list
        }
      },
      components: {
        'cmt-box': commentBox
      }
    });

ref get DOM and components

How to operate DOM in vue

 <div id="app">
    <input type="button" value="Get elements" @click="getElement" ref="mybtn">

    <h3 id="myh3" ref="myh3">Ha ha ha, the weather is so good today!!!</h3>

    <hr>

    <login ref="mylogin"></login>
  </div>
var login = {
      template: '<h1>Login component</h1>',
      data() {
        return {
          msg: 'son msg'
        }
      },
      methods: {
        show() {
          console.log('Method called for subcomponent')
        }
      }
    }

    // Create Vue instance to get ViewModel
    //There is an attribute called ref in vm
    var vm = new Vue({
      el: '#app',
      data: {},
      methods: {
        getElement() {
          // console.log(document.getElementById('myh3').innerText)

          //  ref is the English word [reference] value type and reference type referenceError
          // console.log(this.$refs.myh3.innerText)

          console.log(this.$refs.mylogin.msg)
          this.$refs.mylogin.show()
        }
      },
      components: {
        login
      }
    });

Posted by hannnndy on Sat, 09 Nov 2019 07:52:36 -0800