Sunday, June 10, 2018

[Vue.js][Resolved] Vue cannot read input value by using e.target.value in methods

Error message :


Uncaught TypeError: Cannot read property 'target' of undefined
    at VueComponent.setEvent (test.html:27)
    at input (eval at createFunction (vue.js:10667), <anonymous>:3:253)
    at invoker (vue.js:2029)
    at HTMLInputElement.fn._withTask.fn._withTask (vue.js:1828)

Source code:
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<html>
<head>
<style>
#app {background:#eee; padding:10px;margin:10px;}
#child {background:#456789;color:#fff;padding:10px;margin:10px;}
</style>
</head>
<body>
  <div id="app">
    <p>Company name : <input type="text" v-model="companyName"></p>
    <p>Parent value: {{companyName}}</p>
    <my-cmp :companyname="companyName" @passtoparent="user=$event"></my-cmp>
    <p>Value from child: {{user}}</p>
  </div>
</body>
<script>
Vue.component("my-cmp",{
  props:["companyname"],
  data:function(){
    return {
      "username": ""
    };
  },
  methods:{
    setEvent : function(e){
      this.username = e.target.value;
      this.$emit("passtoparent",this.username);
    }
  },
  template:`
    <div id="child">
    <p>Child compaonent value: {{companyname}}</p>
    <p>Input your name: <input type="text" name="user"                                        v-on:input="setEvent()" /></p>
    <p>{{username}}</p>
    </div>
    `,
});

new Vue({
    el:"#app",
    data:{
      companyName: "",
      user:""
    }
});
</script>
</html>
solution :
Change this line from
v-on:input="setEvent()"
to this
v-on:input="setEvent"

No comments :

Post a Comment