javascript - 从vue中声明的组件获取数据

标签 javascript laravel vue.js

目前我正在尝试了解 Vue 和模板。

我读到您使用 $emit()child ->parent 传递数据

app.js

Vue.component('tweet-postbox', require('./components/tweetPostBox.vue').default);

const app = new Vue({
    el: '#app',
    methods: {
        addTweet (tweet) {
            //from the tweetPostBox.vue postTweet method
            console.log(tweet) 
        }
    }
});

tweetPostBox.vue

<template>
    <div class="post-box">
        <div class="w-100 d-flex align-items-center">
            <div class="profile-image rounded-circle"></div>
            <input v-model="message" type="text" id="tweetText" placeholder="Whats happening?">
        </div>
        <div class="controls d-flex align-items-center w-100">
            <button class="btn btn-primary ml-auto" @click="postTweet" id="postTweet">Tweet</button>
        </div>
    </div>
</template>

<script>
    export default {
        data: function () {
            return {
                message: ''
            }
        },
        methods: {
            postTweet:  async function(){
            let response = await axios.post('/post', {
                message: this.message
            })
            //How to get this response data to the main vue instance?
            this.$emit('addTweet', response);
            }
        }
    }
</script>

我正在尝试从组件文件中将值获取到我的 app.js 中...但控制台没有记录任何内容。我哪里出错了?

更新:添加了 HTML

<div class="container" id="app">
    <tweet-postbox></tweet-postbox>
</div>

最佳答案

您只需将模板更改为:

<div class="container" id="app">
    <tweet-postbox @add-tweet="addTweet"></tweet-postbox>
</div>

@add-tweet 部分为 add-tweet 事件注册一个事件监听器。我使用了 kebab case 来避免浏览器区分大小写的问题。您需要发出同名的事件 this.$emit('add-tweet', response)。请参阅the offical documentation确认烤肉串案例是可行的方法。

="addTweet" 部分将方法 addTweet 指定为监听器。

https://v2.vuejs.org/v2/guide/events.html#Method-Event-Handlers

关于javascript - 从vue中声明的组件获取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57130034/

相关文章:

javascript - ng-change 不能与带选项的 ng-repeat 一起使用,但可以与 ng-options 一起使用

javascript - 设置 CSS3 伪 3d 对象的变换原点

javascript - 如何从渲染器向渲染器中的webview发送IPC消息?

vue.js - 如何为 VueJS 组件创建 v-model 修饰符?

javascript - Chrome 扩展中的 Vue.js

css - 组件样式未在生产中应用-Vue

javascript - 滚动时自动播放视频,但仅播放一次

php - 如何将上传的图片保存到 laravel 中的存储?

php - 找不到四位数的年份数据丢失

php - 通过类型提示将服务提供者注入(inject)到中间件中