I'm trying use v-model to bind my input to the viewport in my WordTranslator component but it isn't rendering, any suggestions?

Viewed 17

This is the component in which im trying to render the input onto the same viewport

<template>
  <div>
    <div>
      <h1>WORD TRANSLATOR</h1>
      <p>Powered by RapidAPI</p>
      <!--The code below is the input in which i attached the v-model to.-->
      <input type="text" name="" id="" class="margin" v-model="message" /><br />
      <select name="" id="" class="margin">
        <option value="">Select A Language</option>
        <option value="">Chinese</option>
        <option value="">Arabic</option>
        <option value="">Indian</option>
        <option value="">Russian</option>
        <option value="">Spanish</option>
        <option value="">Yoruba</option>
        <option value="">Igbo</option>
        <option value="">Hausa</option>
        <option value="">Swedish</option>
        <option value="">French</option>
        <option value="">Ukranian</option>
        <option value="">Xhosa</option>
        <option value="">Korean</option></select
      ><br />
      <p>{{message}}</p>
    </div>
  </div>
</template>

<script>
  export default {
    name: "WordTranslator",
  };
</script>

<style scoped></style>

This is the app vue file for the vue project

<template>
  <!-- <img alt="Vue logo" src="./assets/logo.png">
    <HelloWorld msg="Welcome to Your Vue.js App"/> -->
  <WordTranslator />
</template>

<script>
  // import HelloWorld from './components/HelloWorld.vue'
  import WordTranslator from "./components/WordTranslator.vue";
  export default {
    name: "App",
    components: {
      //HelloWorld
      WordTranslator,
    },
  };
</script>

<style>
  #app {
    text-align: center;
    color: rgb(87, 87, 155);
  }
  .margin {
    margin-bottom: 30px;
  }
</style>
1 Answers

In the file where you're using message, you have to declare message as a reactive reference:

Examples:

<script>
import { ref } from 'vue'
export default {
  name: "WordTranslator",
  setup() {
    const message = ref('')
    return { message }
  }
}
</script>

Alternatively, you could use Options API

export default {
  name: "WordTranslator",
  data: () => ({
    message: ''
  })
}

And this is my preferred syntax (becomes useful when component state is more complex):

import { reactive, toRefs, defineComponent } from "vue"
const WordTranslator = defineComponent({
  setup() {
    const state = reactive({
      message: ""
      // other reactive state props, computed or even methods...
    })
    // other methods...
    return { 
      ...toRefs(state),
      // anything outside of state you want to expose to template
    }
  }
})
export default WordTranslator

All of the above are different ways of writing (almost) the same thing (in fairness, they're compiled slightly differently but, for the purpose of your example, the behavior is the same).

Related