javascriptapivue.jshookstyling

Provide/inject vue


**I'm trying to use the provide/inject vue logic. So my 'firstName' input is defined in the App.vue component as a string "John", I'd like to render it when child component 'Step1' created. But my input is an empty string. How can I fill the input with 'John' string?

https://codesandbox.io/s/intelligent-jasper-teh1im?file=/src/components/Step1.vue**

<template >
  <div class="container">
    <div class="content-wrapper">
      <h1>Step 1</h1>
      <div class="form-group">
        <label>First Name</label
        ><input
          name="name"
          v-model="firstName"
          placeholder="Your first name"
          class="form-control"
          required
        />
      </div>
      <div class="form-group">
        <label>Last Name</label
        ><input
          name="lastname"
          v-model="lastName"
          placeholder="Your last name"
          class="form-control"
          required
        />
      </div>
      <button type="button" @click.prevent="nextStep" class="btn">
        Next step
      </button>
    </div>
    <Button firstName="firstName" lastName="lastName" />
  </div>
</template>

<script>
import Button from "./Button.vue";
export default {
  inject: ["firstName", "lastName"],
  data() {
    return {
      firstName: this.firstName,
      lastName: this.lastName,
    };
  },
  created() {
    // do I need to write smth here ?
  },
  components: {
    Button,
  },
  methods: {
    nextStep() {
      this.$emit("next");
    },
  },
};
</script>

<style scoped>
.form-group {
  display: block;
}
</style>


Solution

  • Your data e.g. firstname is inside the user_detail1 object, so you need to change provide like following to make it work.

    provide() {
        return {
          firstName: this.user_detail1.firstName,
          lastName: this.user_detail1.lastName,
          paymentAmount: this.user_detail2.paymentAmount,
          accountNumber: this.user_detail2.accountNumber
       }
    },