简体   繁体   中英

How to get input data from Vue component

I searched many internet sites but didn't find useful snippets for my problem resolution.
I wanted to achieve simple data passing from input field value in Vue component to Vue root element with a method for data fetching,
eg, simply when I press submit button, the browser alerts me with a msg message instead of undefined .
With Vue technology, I absolutely don't understand how to do this. I spend almost a day trying to understand this. Actually, I don't get how Vue even works with these roots and components even after reading basics nth times. Is there any simple explanation?

Please help!

    <div id="form">
    <button v-on:click="submitBtn">Save</button>
    <custom-form>
    </custom-form>
</div>
<script>

    var testApp = Vue.createApp ({
        methods: {
            submitBtn: function(){
                alert(submit.test)
            }
        }
    })
    
    testComponent.component('custom-form', {
        template: `
            <label>test<input type="text" v-model=value :value=this.test></label>
        ` ,
        data: function() {
            return {
                test: 'msg'
            }
        },
        methods: {
            test: function() {
                return this.test
            }
        }
    })
    
    const vm = testApp.mount('#form')

</script>

simply when I press submit button, the browser alerts me with a msg message instead of undefined .

Here is an example I've just tested that I think will help you:

In app.js file:

Vue.createApp({
  data() {
      return {
        test: ''
      };
  },
  methods: {
      testMessage() {
          return alert(this.test);
      }
  }
}).mount('#form');

And in index.html file:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Vue.js</title>
</head>
<body>
        <div id="form">
            <label for="testInput">Test Message</label>
            <input type="text" id="testInput" v-model="test" />
            <button v-on:click="testMessage">Submit</button>
        </div> 
        
    <script src="https://unpkg.com/vue@next"></script>
    <script src="app.js"></script>
</body>
</html>

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM