【问题标题】:Vuejs how to pass data as a prop to a child componentVuejs如何将数据作为道具传递给子组件
【发布时间】:2018-01-20 16:27:13
【问题描述】:

我构建了以下组件:

var Modal = Vue.component('modal', {

    template: `
        <div id="modal" class="modal">
            <div class="modal-content">
                <p>{{ link }}</p>
            </div>
        </div>
    `,

    props: [
        'link'
    ],

});

我想在我成功发送 axios 帖子后动态更改链接数据。

我的 vue 实例

new Vue({

    el: '#form',

    components: {
        'modal': Modal
    },

    data: {
        userId: '',
        title: '',
        body: '',
        snippetLink: '',
    },

    methods: {

        publish (e) {
            var self = this;
            axios.post('/snippets',  {
                title: this.title,
                body: this.content,
            })
            .then(function (response) {
                console.log("success");
                self.link = response.data.hash; // Here I tried to add the reponse content to the vue component's p
            })
            .catch(function (error) {
              console.log(error);
            })
        },

我的 HTML 标记:

        <modal link=""></modal>
       ...
        <button type="button"                      
                   v-bind:class="{ 'modal-trigger': !isActiveModal }"
                   @click="publish">Publish
                   <i class="material-icons right">send</i>
        </button>

所以我成功地将 axios 帖子发送到我的服务器并获取数据,我想打开一个模态窗口并将数据放在 p 标签中,到目前为止,模态在我的帖子之后弹出,但我不确定我的它不会改变 p 标签的内容。

【问题讨论】:

    标签: javascript vue.js vuejs2 vue-component


    【解决方案1】:

    据我了解,Snippetlink 属性可用于保存来自服务器的数据。

    self.Snippetlink = response.data.hash;
    

    并将 Snippetlink 传递给 sn-p-model 的链接属性

     <snippet-modal :link="Snippetlink"></snippet-modal>
    

    【讨论】:

    • 嗯,它应该返回“SnippetLink”,而不是响应
    • @rupesh_padhye 我会接受它,但您能否添加有关正在发生的事情的信息...
    【解决方案2】:

    rupesh_padhye 的回答是正确的。这只是进一步的解释。

    首先,要将响应数据存储到 Vue 组件中,首先需要为此目的在 data 中定义一个键。所以要使这条线工作:self.link = response.data.hash;,您需要添加link 作为 Vue 组件数据的键:

    data: {
            userId: '',
            title: '',
            body: '',
            snippetLink: '',
            link: ''
        },
    

    如果您的意思是snippetLink,请将行更改为self.snippetLink = response.data.hash;

    其次,要将数据作为道具传递给子组件,您必须指定道具名称以及传递的数据键。例如,要将组件的 link 作为同名道具传递给 snippet-modal 组件,您需要:&lt;snippet-modal :link="link"&gt;&lt;/snippet-modal&gt;

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-07-03
      • 2017-10-31
      • 2019-06-07
      • 2018-08-01
      • 2020-11-23
      • 1970-01-01
      相关资源
      最近更新 更多