簡體   English   中英

Vue:子字符串道具不會呈現

[英]Vue: Child string prop wont render

您好我是 vue 新手,正在嘗試了解它的單向數據綁定模型組件注冊和傳遞道具。

在我的index.js中,我有我的父組件,我現在想在其中渲染一個孩子

import Vue from 'vue'
import StyledTitle from './components/StyledTitle'

new Vue({
  el: '#app',
  components: {
    StyledTitle,
  },
})

子組件是StyledTitle.js

import Vue from 'vue'
import styled from 'vue-styled-components'

const StyledTitle = styled.h1`
  font-size: 1.5em;
  text-align: center;
  color: #ff4947;
  &:hover,
  &:focus {
    color: #f07079;
  }
`

Vue.component('styled-title', {
  props: ['text'],
  components: {
    'styled-title': StyledTitle,
  },
  template: `<StyledTitle>{{ text }}</StyledTitle>`,
})

export default StyledTitle

最后,我的 HTML 是我希望呈現紅色的 Hi

<div id="app">
   <styled-title text="Hi"></styled-title>
</div>

HI 沒有顯示,並且 props 值未定義。 從反應過來,所以想知道為什么這不起作用,謝謝!

我的vue devtools的ps截圖在此處輸入圖像描述

問題是您的StyledTitle.js文件導出了一個普通樣式的<h1>組件,該組件使用默認插槽作為其內容,而不是接受text道具的自定義組件。

如果您仍然熱衷於使用基於 prop 的組件,則需要將其導出,而不是從vue-styled-components導出。 在這種情況下,您也應該避免全局組件注冊。

例如

// StyledTitle.js
import styled from 'vue-styled-components'

// create a styled title locally
const Title = styled.h1`
  font-size: 1.5em;
  text-align: center;
  color: #ff4947;
  &:hover,
  &:focus {
    color: #f07079;
  }
`

// now export your custom wrapper component
export default {
  name: 'StyledTitle',
  props: ['text'],
  components: {
    Title, // locally register your styled Title as "Title"
  },
  template: `<Title>{{ text }}</Title>`,
})

鑒於您的組件不維護任何狀態,您可以將其設為純功能 使用渲染函數也會有所幫助,特別是如果您的 Vue 運行時不包含模板編譯器(這是大多數 Vue CLI 應用程序的默認設置)

export default {
  name: 'StyledTitle',
  functional: true,
  props: { text: String },
  render: (h, { props }) => h(Title, props.text)
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM