简体   繁体   English

如何在 Vue.js 中的脚本部分为组件设置道具(无渲染)

[英]How to set props to component in Vue.js in script section (without rendering)

I need to import component A with props and pass it to another component B. It must be rendered in component B.我需要使用 props 导入组件 A 并将其传递给另一个组件 B。它必须在组件 B 中呈现。

import MyComponent from '/MyComponent.vue'

computed: {
    compnt: function () {
        var comp = MyComponent      
        // How can I set props to MyComponent? 
        return comp 
    }
}

What should I do to set props to component A?我应该怎么做才能为组件 A 设置道具?

If you only want to share data between components it's best to use vuex .如果你只想在组件之间共享数据,最好使用vuex You can define a variable in the state like this您可以像这样在state中定义一个变量

# store/store.js
//...
state: {
  count: 0
}
// ...

And use it in any component you want like this.并像这样在您想要的任何组件中使用它。

<template>
  <span>{{ count }}</span>
</template>
<script>
export default {
  // ...
  computed: mapState(['count'])
  // ...
}
</script>

You can follow this tutorial for more information您可以按照本教程了解更多信息

If you want to share the data between components you can use below solution如果你想在组件之间共享数据,你可以使用下面的解决方案

Create the EventBus.js file创建 EventBus.js 文件

import Vue from 'vue';

export const EventBus = new Vue();

In your component file use below code在您的组件文件中使用以下代码

import { EventBus } from "../EventBus.js";
export default { 
  mounted() {
      var myData = "Hi"; 
      EventBus.$emit("sendIndex", myData );
    };
  },
};

Access your data in the component as访问组件中的数据

import { EventBus } from "../EventBus.js";
export default { 
  mounted() {
    EventBus.$on('sendIndex', data => {
      console.log(data)
    });
  },
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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