Home » vue » Getting the computed method to another components (Vuejs)

Getting the computed method to another components (Vuejs)

Posted by: admin November 26, 2021 Leave a comment

Questions:

i wanted to get the computed data and display in another component. However i put the computed in my app.vue and try to call this computed using :style="inputStyles" in my ChangeBackground.vue . But when i try to do this it showing error that " Property or method "inputStyles" is not defined on the instance but referenced during render" Can someone help me? Thank you

You can access the code here:
https://codesandbox.io/s/hardcore-morning-5ch1u?file=/src/components

Here is the code:

App.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>

ChangeBackground.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>
Answers:

You should pass it as prop as you did with msg :

App.vue

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

ChangeBackground.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>