鍍金池/ 問答/HTML/ vue組件引用未報錯,但子組件A渲染成功,子組件B渲染失敗

vue組件引用未報錯,但子組件A渲染成功,子組件B渲染失敗

有兩個組件TranslateForm.vue和TranslateText.vue掛載在根組件時TranslateForm.vue成功渲染,TranslateText.vue只渲染出來一個<div></div>標(biāo)簽,控制臺未報錯圖片描述

TranslateForm.vue

<template>
  <div>
    <!--加上頁面修飾符,提交時就不回再重載頁面-->
    <form v-on:submit.prevent="formSubmit">
      <input type="text" v-model="text" placeholder="輸入需要翻譯的內(nèi)容"/>
      <select>
        <option value ="en">English</option>
      </select>
      <input type="submit" value="翻譯"/>
    </form>
  </div>
</template>

<script>
export default {
  name: 'TranslateForm',
  data: function () {
    return {
      text: ''
    }
  },
  methods: {
    formSubmit: function () {
      this.$emit('formSubmit', this.text)
    }
  }
}
</script>

<style></style>

TranslateText.vue

<template>
  <div>
    <p>111</p>
    <h2>{{translatedText}}</h2>
  </div>
</template>

<script>
export default {
  name: 'TranslateText',
  props: [
    'translatedText'
  ]
}
</script>

<style></style>

APP.vue

<template>
  <div id="app">
    <h2>簡單翻譯</h2><span>簡單/易用/便捷</span>
    <TranslateForm v-on:formSubmit="textTranslate"></TranslateForm>
    <TranslateText v-text="translatedText"></TranslateText>
  </div>
</template>

<script>
import TranslateForm from './components/TranslateForm.vue'
import TranslateText from './components/TranslateText.vue'
import md5 from 'blueimp-md5'
import $ from 'jquery'

export default {
  name: 'App',
  data: function () {
    return {
      appKey: '47bb6e424790df89',
      key: 'NH2VxBadIlKlT2b2qjxaSu221dSC78Ew',
      salt: (new Date()).getTime(),
      from: '',
      to: 'en',
      translatedText: ''
    }
  },
  components: {
    TranslateForm, TranslateText
  },
  methods: {
    textTranslate: function (text) {
      $.ajax({
        url: 'http://openapi.youdao.com/api',
        type: 'post',
        dataType: 'jsonp',
        data: {
          q: text,
          appKey: this.appKey,
          salt: this.salt,
          from: this.from,
          to: this.to,
          sign: md5(this.appKey + text + this.salt + this.key)
        },
        success: function (data) {
          console.log(data.translation[0])
          this.translatedText = data.translation[0]
        }
      })
    }
  }
}
</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;
  }
</style>
回答
編輯回答
情殺

v-text會把標(biāo)簽中的內(nèi)容替換掉,父組件值為空,所以就沒東西嘍

2017年10月10日 02:00
編輯回答
鐧簞噯

引用方式改成以下:

<TranslateText :translated-text ="translatedText"></TranslateText>
<TranslateText v-text="translatedText"></TranslateText>
<!-- 等價于 -->
<TranslateText>{{translatedText}}</TranslateText>

使用上面這種方式,如果子組件中沒有slot,里面的內(nèi)容會被丟棄,不會渲染:

clipboard.png

參考鏈接

  1. vue slot
2017年1月19日 22:54