Home > Blockchain >  (Vue.js) Importing values from one component to another, not sure if it can be done with props
(Vue.js) Importing values from one component to another, not sure if it can be done with props

Time:06-24

I'm trying to learn vue and hit a small roadbump - is there a way for me to make this work? I want to push a new value into my items array with my Button component so then i can render it with the v-for. I know it would much be easier to put everything into one file, just curious if it can be done this way. Here is the code:

https://codesandbox.io/s/mystifying-antonelli-7o6m6o?file=/src/App.vue

any help would be much appreciated :)

CodePudding user response:

Sure this can be done the way you would like. One way to do it is to define the variables and the add function in the App.vue.

<script setup>
import { ref } from "vue";

const name = ref("");
const amount = ref(0);
const items = ref([]);

const addItem = () => {
  items.value.push = { name: name.value, amount: amount.value };
  name.value = "";
  amount.value = 0;
};
</script>

Bind name and amount with your inputs via v-model and bind addItem to your button with @click. You can use items as a prop for your ItemList component.

Your components need changes to work, but I hope this will give you some direction. Perhaps first make it work with plain html input and button elements and use {{ items }} to render the items array. Once that works you can create the custom components.

Hope this helps.

  • Related