Vue-Material切换主题报错:Property 'material'不存在于类型'Vue'
First, let's tackle the TypeScript error you're facing: Property 'material' does not exist on type 'Vue'. This happens because TypeScript doesn't recognize the material object that Vue-Material attaches to the root Vue instance. Here's a step-by-step solution to fix this and implement theme switching properly:
1. Register Your Second Theme in SCSS
First, add your myDark theme alongside your default theme in your SCSS file:
@import "~vue-material/dist/theme/engine"; // Register default light theme @include md-register-theme("default", ( primary: md-get-palette-color(lime, A200), accent: md-get-palette-color(green, 500), secondary: #a10b4a, raised: #000000, theme: light )); // Register custom dark theme @include md-register-theme("myDark", ( primary: md-get-palette-color(blue, A400), // Adjust these colors to your preference accent: md-get-palette-color(purple, 600), theme: dark )); @import "~vue-material/dist/theme/all";
2. Fix TypeScript Typings
Create a type declaration file (e.g., src/types/vue-material.d.ts) to extend Vue's type definitions and inform TypeScript about the material object:
declare module 'vue/types/vue' { interface Vue { $root: Vue & { material: { setCurrentTheme: (themeName: string) => void; currentTheme: string; }; }; } }
Ensure your tsconfig.json includes this directory in the include array so TypeScript picks up the declaration:
{ "include": ["src/**/*.ts", "src/**/*.d.ts"] }
3. Implement the Theme Switch Method
Now you can safely call setCurrentTheme in your component without TypeScript errors. Here's a basic implementation:
switchMyTheme = () => { this.$root.material.setCurrentTheme('myDark'); };
If you want to toggle between themes instead of switching to just one, add a check for the current theme:
switchMyTheme = () => { const currentTheme = this.$root.material.currentTheme; this.$root.material.setCurrentTheme(currentTheme === 'default' ? 'myDark' : 'default'); };
4. Double-Check Vue-Material Initialization
Make sure you've properly initialized Vue-Material in your main.ts file to ensure the material object is attached to the root instance:
import Vue from 'vue'; import VueMaterial from 'vue-material'; import 'vue-material/dist/vue-material.min.css'; Vue.use(VueMaterial); new Vue({ render: h => h(App), }).$mount('#app');
This should resolve the error and let you switch themes seamlessly!
内容的提问来源于stack exchange,提问作者Nikola Lukic

