如果无法从服务器中提取数据,我试图弹出甜味警报。
我在main.js中导入了甜警报:
import VueSweetalert2 from 'vue-sweetalert2'
import 'sweetalert2/dist/sweetalert2.min.css'
const app = createApp(App)
app.use(VueSweetalert2)
app.mount('#app')在Table.vue组件中,我试图调用swal,但是得到了一个错误:
<script>
import axios from 'axios'
import { onMounted, ref } from 'vue'
export default {
setup() {
let transactions = ref([])
onMounted(() => {
getTransactions()
})
async function getTransactions() {
try {
let { data } = await axios.get('http://127.0.0.1:8000/api/transactions')
transactions.value = data.data
} catch(e) {
this.$swal('Something went wrong.')
}
}
return {
transactions
}
}
}
</script>有什么解决办法吗?
发布于 2021-07-23 21:41:58
您不能使用this作为setup()中的组件实例,因为尚未创建组件。获得该$swal属性还有其他方法。
vue-sweetalert2通过app.config.globalProperties.$swal或道具公开SweetAlert。
在复合API中使用它的一个简单方法是通过inject()。
import { inject } from 'vue'
export default {
setup() {
const swal = inject('$swal')
async function getTransactions() {
//...
swal('Something went wrong.')
}
}
}但是,在本例中,vue-sweetalert2文档建议直接使用sweetalert2:
当使用"Vue3: Composition“时,最好不要使用这个包装器。直接调用sweetalert2更加实用。
您可以像这样直接使用sweetalert2:
import { onMounted, inject } from 'vue'
import Swal from 'sweetalert2'
export default {
name: 'App',
setup() {
async function getTransactions() {
//...
Swal.fire('Something went wrong.')
}
onMounted(() => getTransactions())
}
}发布于 2022-01-05 12:25:42
在main.js文件中
import VueSweetalert2 from 'vue-sweetalert2';
import 'sweetalert2/dist/sweetalert2.min.css';
const app = createApp(App);
app.use(VueSweetalert2);
window.Swal = app.config.globalProperties.$swal;
app.mount("#app");在组合API中使用Swal.fire()
export default {
setup() {
function yourFunctionName() {
Swal.fire('Hello !')
}
}
}https://stackoverflow.com/questions/68452269
复制相似问题