0

我想获取计算数据并显示在另一个组件中。但是,我将计算结果放在我的 app.vue 中,并尝试在我的 ChangeBackground.vue 中使用 :style="inputStyles" 调用这个计算结果。但是当我尝试这样做时,它显示错误“属性或方法“inputStyles”未在实例上定义但在渲染期间被引用”有人可以帮助我吗?谢谢

您可以在此处访问代码: https ://codesandbox.io/s/hardcore-morning-5ch1u?file=/src/components

这是代码:

应用程序.vue

<template>
  <div id="app">
    <ChangeBackground msg="Hello Vue in CodeSandbox!" />
  </div>
</template>

<script>
import ChangeBackground from "./components/ChangeBackground";
export default {
  name: "App",
  components: {
    ChangeBackground,
  },

  data() {
    return {
      bgColor: "red",
    };
  },
  created() {
    this.bgColor = "#F6780D";
  },
  computed: {
    inputStyles() {
      return {
        background: this.bgColor,
      };
    },
  },
};
</script>

<style>
#app {
  font-family: "Avenir", Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}
body {
  background-color: blue;
}
</style>

更改背景.vue

<template>
  <div class="hello" :style="inputStyles">
    <h1>{{ msg }}</h1>
  </div>
</template>

<script>
export default {
  name: "HelloWorld",
  data() {
    return {
      msg: "Getting the computed area here to change the background",
    };
  },
};
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style>
h1,
h2 {
  font-weight: bold;
}
ul {
  list-style-type: none;
  padding: 1rem;
}
li {
  display: inline-block;
  margin: 0 10px;
}
a {
  color: #42b983;
}
</style>
4

1 回答 1

2

你应该把它作为道具传递给你msg

应用程序.vue

<ChangeBackground msg="Hello Vue in CodeSandbox!" :input-styles="inputStyles" />

更改背景.vue

<template>
  <div class="hello" :style="inputStyles">
    <h1>{{ msg }}</h1>
  </div>
</template>

<script>
export default {
  name: "HelloWorld",
  props:["inputStyles"],//⬅
  data() {
    return {
      msg: "Getting the computed area here to change the background",
    };
  },
};
</script>
于 2021-08-05T09:10:30.307 回答